<?php
/**
 * @author       Sixe Team
 * @email        info@eee-eee.com
 * @url          http://www.eee-eee.com
 * @copyright    Copyright (C) 2010 - 2019 Sixe Information Technology Limited. All rights reserved.
 * @license      GNU General Public License version 2 or later; see LICENSE.txt
 * @date         2019/10/01 10:00
 */

defined('_JEXEC') or die;
JLoader::register('SixeWorkFlowMenuHelper', JPATH_SITE . '/components/com_sixeworkflow/helpers/menu.php');

/**
 * Example Content Plugin
 *
 * @since  1.6
 */
class PlgSystemSixeWorkflow extends JPlugin
{
	var $formpath = __DIR__;

	protected $autoloadLanguage = true;

	public function __construct(& $subject, $config)
	{
		parent::__construct($subject, $config);
		$this->loadLanguage();
	}

	public function onBeforeRender()
	{
		$app = JFactory::getApplication();
		$doc = JFactory::getDocument();
		$user = JFactory::getUser();
		if ($app->isSite() && !$user->guest) {
			$doc->addStyleSheet(JUri::root(true) . '/plugins/system/sixeworkflow/assets/css/plgsixeworkflow.css');

			$js = "jQuery(function($){
	$(document).ready(function(){
		function CheckMessage(){
			$.ajax({
				url:'" . JUri::root(true) . "/index.php?option=com_sixeworkflow&task=menus.checknew',
				dataType: 'json'
			}).done(function(data){
				if(data.count > 0){
					var total=data.views;
					$('.user-avatar').find('span.total').html(data.count).show();
					for(var view in total){
						if(total[view] > 0){
							$('.user-center-menus').find('.workflow-menu-'+view+' .total').html(total[view]).show();
						}else{
							$('.user-center-menus').find('.workflow-menu-'+view+' .total').html(total[view]).hide();
						}
					}
				}else{
					$('.user-avatar').find('span.total').html(data.count).hide(); 
				}
			})
		}
		CheckMessage();
		var time=window.setInterval(CheckMessage,10000);
	});
});";
			$doc->addScriptDeclaration($js);
		}
	}

	public function onAfterRender()
	{
		$app = JFactory::getApplication();

		$user = JFactory::getUser();
		if ($app->isSite() && !$user->guest && $app->input->get('tmpl') != 'component') {

			$menus = SixeWorkFlowMenuHelper::_();
			$path = JPluginHelper::getLayoutPath('system', 'sixeworkflow');
			ob_start();
			include $path;
			$menu = ob_get_clean();
			$menu .= '</body>';
			$body = $app->getBody();
			$body = preg_replace('@^\s*</body>\s*$@msU', $menu, $body);
			$app->setBody($body);
		}
	}


	public function onContentPrepareForm($form, $data)
	{
		$app = JFactory::getApplication();
		$option = $app->input->getCmd('option', 'com_content');
		if (!($form instanceof JForm)) {
			$this->_subject->setError('JERROR_NOT_A_FORM');
			return false;
		}

		$name = $form->getName();

		if (!in_array($name, array('com_categories.categorycom_content', 'com_content.article'))) {
			return true;
		}
		$onchange = '';
		if ($form->getField('catid')) {
			if ($option == 'com_sixeworkflow') {
				$onchange = "if (confirm('" . JText::_('PLG_SYSTEM_SIXEWORKFLOW_CATID_FIELD_ONCHANGE') . "')) { categoryHasChanged(this);}";

			} else {
				$onchange = $form->getFieldAttribute('catid', 'onchange', '');
			}
		}

		JForm::addFormPath($this->formpath . '/form');
		$form->loadFile($name, true);
		if ($form->getField('catid')) {
			$form->setFieldAttribute('catid', 'onchange', $onchange);
		}

		return true;
	}


	public function onContentAfterSave($context, $item, $isNew = false, $data = array())
	{
		if (!in_array($context, array('com_categories.category'))) {
			return true;
		}
		$data = (object)$data;
		$db = JFactory::getDbo();
		if ($item->id > 0) {
			$query = $db->getQuery(true);
			$query->delete($query->qn('#__workflow_categories'))
				->where('category_id=' . $item->id);
			$db->setQuery($query)->execute();
			if ($data->workflow > 0) {
				$newObj = new stdClass;
				$newObj->category_id = (int)$item->id;
				$newObj->workflow_id = $data->workflow;
				$db->insertObject('#__workflow_categories', $newObj);
			}
		}

		return true;
	}


	public function onContentAfterDelete($context, $article)
	{
		if (!in_array($context, array('com_categories.category', 'com_content.article'))) {
			return true;
		}
		if ($context == 'com_content.article') {
			$db = JFactory::getDbo();
			$query = $db->getQuery(true);
			$query->delete($query->qn('#__workflow_flows'))
				->where('content_id=' . $article->id);
			$db->setQuery($query)->execute();
			$query = $db->getQuery(true);
			$query->delete($query->qn('#__workflow_contents'))
				->where('content_id=' . $article->id);
			$db->setQuery($query)->execute();
			$query = $db->getQuery(true);
			$query->delete($query->qn('#__workflow_messages'))
				->where('content_id=' . $article->id);
			$db->setQuery($query)->execute();

			return true;
		}
		if ($context == 'com_categories.categoryss') {
			$db = JFactory::getDbo();
			$query = $db->getQuery(true);
			$query->delete($query->qn('#__workflow_categories'))
				->where('category_id =' . $article->id);
			$db->setQuery($query)->execute();

			return true;
		}

		return true;
	}


	public function onContentPrepareData($context, $data)
	{
		if (!in_array($context, array('com_categories.category', 'com_content.article'))) {
			return true;
		}
		$app = JFactory::getApplication();
		$data = (object)$data;
		if ($context == 'com_content.article' && $app->isSite() && $app->input->get('option', 'com_content') == 'com_content') {
			JModelLegacy::addIncludePath(JPATH_ADMINISTRATOR . '/components/com_sixeworkflow/models', 'SixeWorkFlowModel');
			$model = JModelLegacy::getInstance('Article', 'SixeWorkFlowModel', array('ignore_request' => true));
			$workflow_article = $model->getFlowContent($data->id);

			if ($workflow_article->content_id > 0) {
				$app->enqueueMessage(JText::_('JERROR_ALERTNOAUTHOR'), 'error');

				$app->redirect($this->getReturnPage());
			} else {
				return true;
			}
		}

		$db = JFactory::getDbo();
		if ($data->id > 0) {
			$query = $db->getQuery(true);
			$query->select('workflow_id')
				->from('#__workflow_categories')
				->where('category_id=' . $data->id);
			$db->setQuery($query);
			$workflow = $db->loadColumn();
			$data->workflow = $workflow;
		}

		return true;
	}


	public function onUserAfterLogin($options)
	{
		//$app=JFactory::getApplication();
		//$app->SetUserState('users.login.form.return','index.php?option=com_sixeworkflow&view=messages');
	}


	public function onContentPrepare($context, &$row, &$params, $page = 0)
	{
		$app = JFactory::getApplication();
		if (!in_array($context, array('com_content.article', 'com_content.category', 'com_sixeworkflow.message'))) {
			return true;
		}
		$article = (object)$row;
		if ($context == 'com_sixeworkflow.message') {
			$params = $app->getParams('com_sixeworkflow');
			$user = JFactory::getUser($article->from_user);
			$to_user = JFactory::getUser($article->to_user);
			$uri = JUri::getInstance();
			$base = $uri->toString(array('scheme', 'user', 'pass', 'host', 'port'));
			$link = $base . JRoute::_('index.php?option=com_sixeworkflow&view=articleform&task=article.edit&a_id=' . $article->content_id, false);
			$emailSubject = '';
			$emailBody = '';

			if ($article->type == 1) {
				$emailSubject = JText::sprintf('PLG_SYSTEM_SIXEWORKFLOW_SUBMIT_MESSAGE_TITLE', $user->name);
				$emailBody = JText::sprintf('PLG_SYSTEM_SIXEWORKFLOW_SUBMIT_MESSAGE_BODY', $user->name, $link, $article->message);
				if ($params->get('email_submit_body', '') != '') {
					$emailBody = $params->get('email_submit_body');
				}
				if (!$params->get('email_submit', 0)) {
					return true;
				}
			}

			if ($article->type == 2) {
				$emailSubject = JText::sprintf('PLG_SYSTEM_SIXEWORKFLOW_REJECT_MESSAGE_TITLE', $user->name);
				$emailBody = JText::sprintf('PLG_SYSTEM_SIXEWORKFLOW_REJECT_MESSAGE_BODY', $user->name, $link, $article->message);
				if ($params->get('email_reject_body', '') != '') {
					$emailBody = $params->get('email_reject_body');
				}
				if (!$params->get('email_reject', 0)) {
					return true;
				}
			}

			$emailBody = str_replace('{from_name}', $user->name, $emailBody);
			$emailBody = str_replace('{to_name}', $to_user->name, $emailBody);
			$emailBody = str_replace('{title}', $article->title, $emailBody);
			$emailBody = str_replace('{url}', $link, $emailBody);
			$emailBody = str_replace('{message}', $article->message, $emailBody);
			$mail = JFactory::getMailer()->sendMail(
				$app->get('mailfrom'),
				$app->get('fromname'),
				$to_user->email,
				$emailSubject,
				$emailBody
			);

			return true;
		}
		if ($article->state != 10) {
			return true;
		} else {
			if ($context == 'com_content.category') {

				$row->title = JText::_('PLG_SYSTEM_SIXEWORKFLOW_ARTICLE_UNPUBLISHED');
				$row->id = '';
				$row->alias = '';
				$row->slug = '';
				$row->text = '';
				$row->introtext = '';
				$row->created_by = 0;
				$row->fulltext = '';
				return true;
			}
		}
		$user = JFactory::getUser();
		if ($article->created_by == $user->id) {
			return true;
		}

		$app = JFactory::getApplication();
		JModelLegacy::addIncludePath(JPATH_ADMINISTRATOR . '/components/com_sixeworkflow/models', 'SixeWorkFlowModel');
		$model = JModelLegacy::getInstance('Article', 'SixeWorkFlowModel', array('ignore_request' => false));
		$workflow_article = $model->getFlowContent($article->id);
		$userflow = $model->getFlow($article->catid, $user->id);
		if (!$workflow_article || !$userflow) {
			$app->enqueueMessage(JText::_('JERROR_ALERTNOAUTHOR'), 'error');
			$app->redirect('index.php');
		}

		if ($workflow_article && $userflow) {
			$temp = array_diff($userflow, array($workflow_article->start_flow));
			if (count($temp) == 0) {
				$app->enqueueMessage(JText::_('JERROR_ALERTNOAUTHOR'), 'error');
				$app->redirect('index.php');
			}
		}
	}


	protected function getReturnPage()
	{
		$return = JFactory::getApplication()->input->get('return', null, 'base64');

		if (empty($return) || !JUri::isInternal(base64_decode($return))) {
			return JUri::root();
		} else {
			return base64_decode($return);
		}
	}

}
